<?php
namespace app\manage\controller;
use org\Collection;
class CollectionArticle extends Base
{


    private $db;

    //HTML标签
    private $html_tag = array("<p([^>]*)>(.*)</p>[|]"=>'<p>', "<a([^>]*)>[|]"=>'<a>',"</a>[|]"=>'</a>',"<h1([^>]*)>[|]"=>'<h1>',"</h1>[|]"=>'</h1>',"<script([^>]*)>(.*)</script>[|]"=>'<script>', "<iframe([^>]*)>(.*)</iframe>[|]"=>'<iframe>', "<table([^>]*)>(.*)</table>[|]"=>'<table>', "<span([^>]*)>(.*)</span>[|]"=>'<span>', "<b([^>]*)>(.*)</b>[|]"=>'<b>', "<img([^>]*)>[|]"=>'<img>', "<object([^>]*)>(.*)</object>[|]"=>'<object>', "<embed([^>]*)>(.*)</embed>[|]"=>'<embed>', "<param([^>]*)>(.*)</param>[|]"=>'<param>', '<div([^>]*)>[|]'=>'<div>', '</div>[|]'=>'</div>', '<!--([^>]*)-->[|]'=>'<!-- -->','[reset]要换的中文[|]改成的中文'=>'替换中文');

    //网址类型
    private $url_list_type = array();
//前置操作定义
    protected $beforeActionList = [
        'beforeIndex' =>  ['only'=>'index'],
    ];
    public function _initialize()
    {
        parent::_initialize();
        $this->db = db("CollectionNode");
        $this->assign('html_tag',$this->html_tag);
        $this->assign('url_list_type', array('1'=>'序列网址', '2'=>'多条网址', '3'=>'单一网页', '4'=>'RSS'));

    }
    private function listinfo($obj,$where,$pagesize,$order){
        $list    = $obj->where($where)->order($order)->paginate($pagesize);
        $lists   = ['lists'=>$list,'pages'=>$list->render()];
        return $lists;
    }
    public function beforeIndex(){
        $this->assign('list_table',true);
        $this->_data = [
            'test'    => [
                'c' => 'CollectionArticle',
                'a' => 'publishTest',
                'str'    => '<a data-height="410" data-width="520" data-id="test" data-uri="%s" data-title="采集测试" class="J_showdialog" href="javascript:;">测试</a>',
                'param' => ['nodeid'=>'@id@'],
                'isajax' => 1,
                'replace'=> ''
            ],
            'copy'    => [
                'c' => 'CollectionArticle',
                'a' => 'colCopy',
                'str'    => '<a data-height="410" data-width="520" data-id="copy" data-uri="%s" data-title="复制" class="J_showdialog" href="javascript:;">复制</a>',
                'param' => ['nodeid'=>'@id@'],
                'isajax' => 1,
                'replace'=> ''
            ],
        ];
    }
    /**
     * node list
     */
    public function index() {
        $lists         = $this->listinfo($this->db,[],20,'nodeid DESC');
        $pages         = $lists['pages'];
        $nodelist      = $lists['lists'];
        $this->assign('options', $this->check());
        $this->assign('pages',$pages);
        $this->assign('lists',$nodelist);
        return $this->fetch();
    }

    private function get_one($obj,$where=array(),$field='*'){
    return $obj->field($field)->where($where)->find();
}
    /**
     * add node
     */
    public function add() {
        header("Cache-control: private");
        if(request()->isPost()) {
            $data = isset($_POST['data']) ? $_POST['data'] :  $this->error('参数错误');
            $customize_config = isset($_POST['customize_config']) ? $_POST['customize_config'] :  '';
            if (!$data['name'] = trim($data['name'])) {
                $this->error('请填写采集点名称');
            }
            if ($this->get_one($this->db,array('name'=>$data['name']))) {
                $this->error('采集点名称已存在');
            }
            $data['urlpage'] = isset($_POST['urlpage'.$data['sourcetype']]) ? $_POST['urlpage'.$data['sourcetype']] : $this->error('请填写网址规则');
            $data['customize_config'] = array();
            if (is_array($customize_config)) foreach ($customize_config['en_name'] as $k => $v) {
                if (empty($v) || empty($customize_config['name'][$k])) continue;
                $data['customize_config'][] = array('name'=>$customize_config['name'][$k], 'en_name'=>$v, 'rule'=>$customize_config['rule'][$k], 'html_rule'=>$customize_config['html_rule'][$k]);
            }
            $data['customize_config'] = array2string($data['customize_config']);
            if ($this->db->insert($data)) {
                $this->success('添加采集点成功',url('index'));
            } else {
                $this->error('添加采集点失败');
            }
        } else {
           return $this->fetch();
        }

    }

    //修改采集配置
    public function edit() {
        $nodeid = input('param.id/d',0);
        if(!$nodeid) $this->error('参数错误');
        $data = $this->get_one($this->db,['nodeid'=>$nodeid]);
        if(request()->isPost()) {
            $datas = $data;
            unset($data);
            $data = isset($_POST['data']) ? $_POST['data'] :  $this->error('参数错误');
            $customize_config = isset($_POST['customize_config']) ? $_POST['customize_config'] :  '';
            if (!$data['name'] = trim($data['name'])) {
                $this->error('请填写采集点名称');
            }

            if ($datas['name'] != $data['name']) {
                if ($this->get_one($this->db,['name'=>$data['name']])) {
                    $this->error('采集点名称已存在');
                }
            }

            $data['urlpage'] = isset($_POST['urlpage'.$data['sourcetype']]) ? $_POST['urlpage'.$data['sourcetype']] : $this->error('请填写网址规则');
            $data['customize_config'] = array();
            if (is_array($customize_config)) foreach ($customize_config['en_name'] as $k => $v) {
                if (empty($v) || empty($customize_config['name'][$k])) continue;
                $data['customize_config'][] = ['name'=>$customize_config['name'][$k], 'en_name'=>$v, 'rule'=>$customize_config['rule'][$k], 'html_rule'=>$customize_config['html_rule'][$k]];
            }
            $data['customize_config'] = array2string($data['customize_config']);
            if ($this->db->where(['nodeid'=>$nodeid])->update($data)) {
                $this->success('修改成功',url('index',['menuid'=>230]));
            } else {
               $this->error('修改失败');
            }
        } else {
            if (isset($data['customize_config'])) {
                $data['customize_config'] = string2array($data['customize_config']);
            }
         $this->assign('info',$data);
         return $this->fetch();
        }
    }

    //复制采集
    public function colCopy() {
        $nodeid = input('param.nodeid/d',0);
        if(!$nodeid) $this->ajaxReturn(0,'参数错误');
        if ($data = $this->get_one($this->db,array('nodeid'=>$nodeid))) {
            if (request()->isPost()) {
                unset($data['nodeid']);
                $name = isset($_POST['name']) && trim($_POST['name']) ? trim($_POST['name']) : $this->ajaxReturn(0,'请填写采集点名称');
                if ($this->get_one($this->db,array('name'=>$name), 'nodeid')) {
                    $this->ajaxReturn(0,'采集点已存在');
                }
                $data['name'] = $name;
                //$data = new_addslashes($data);
                if ($this->db->insert($data)) {
                  $this->ajaxReturn(1,'复制成功','','copy');
                } else {
                   $this->ajaxReturn(0,'复制失败');
                }
            } else {
                $this->assign('name',$data['name']);
                $this->assign('id',$data['nodeid']);
               $response = $this->fetch();
                $this->ajaxReturn(1,'',$response);
            }
        } else {
            $this->error('采集点不存在');
        }
    }

    //URL配置显示结果
    public function publishurl() {
        $sourcetype     = isset($_GET['sourcetype']) && intval($_GET['sourcetype']) ? intval($_GET['sourcetype']) : $this->ajaxReturn(0,'参数错误');
        $pagesize_start = isset($_GET['pagesize_start']) && intval($_GET['pagesize_start']) ? intval($_GET['pagesize_start']) : 1;
        $pagesize_end   = isset($_GET['pagesize_end']) && intval($_GET['pagesize_end']) ? intval($_GET['pagesize_end']) : 10;
        $par_num        = isset($_GET['par_num']) && intval($_GET['par_num']) ? intval($_GET['par_num']) : 1;
        $urlpage        = isset($_GET['urlpage']) && trim($_GET['urlpage']) ? trim($_GET['urlpage']) : $this->ajaxReturn(0,'url地址错误');
        $this->assign('sourcetype',$sourcetype);
        $this->assign('pagesize_start',$pagesize_start);
        $this->assign('pagesize_end',$pagesize_end);
        $this->assign('par_num',$par_num);
        $this->assign('urlpage',urldecode($urlpage));
        $response = $this->fetch();
        $this->ajaxReturn(1, '', $response);
    }
    public function delete(){
        $mod = $this->db;
        $pk  = $mod->getPk();
        $ids = trim(input('id'), ',');
        if ($ids) {
            if (false !== $mod->where(['nodeid'=>['in',$ids]])->delete()) {
                $content_db = db('CollectionContent');
                $content_db->where(['nodeid'=>['in',$ids]])->delete();
                request()->isAjax() && $this->ajaxReturn(1, '操作成功');
                $this->success('操作成功');
            } else {
                request()->isAjax() && $this->ajaxReturn(0, '操作失败');
                $this->error('操作失败');
            }
        } else {
            request()->isAjax() && $this->ajaxReturn(0,'参数错误');
            $this->error('参数错误');
        }
    }

    //测试文章URL采集
    public function publishTest() {
        $nodeid = input('param.nodeid/d',0);
        if(!$nodeid) $this->error('参数错误');
        if ($data = $this->get_one($this->db,['nodeid'=>$nodeid])) {
            $urls = Collection::url_list($data, 1);
            if (!empty($urls)) foreach ($urls as $v) {
                $url = Collection::get_url_lists($v, $data);
            }
            $this->assign('url',$url);
            $this->assign('nodeid',$data['nodeid']);
            $response = $this->fetch();
            $this->ajaxReturn(1, '', $response);
        } else {
            $this->ajaxReturn(0,'采集点不存在');
        }
    }

    //测试文章内容采集
    public function publicTestContent() {
        $url = urldecode(input('param.url'));
        if(!$url) $this->ajaxReturn(0,'url地址不存在');
        $nodeid = input('param.nodeid/d',0);
        if(!$nodeid) $this->ajaxReturn(0,'参数错误');
        if ($data = $this->get_one($this->db,['nodeid'=>$nodeid])) {
            $contents = Collection::get_content($url, $data);
            foreach ($contents as $_key=>$_content) {
                if(trim($_content)=='') $contents[$_key] = '◆◆◆◆◆◆◆◆◆◆'.$_key.' empty◆◆◆◆◆◆◆◆◆◆';
            }
           print_r($contents);
        } else {
            $this->ajaxReturn(0,'数据不存在');
        }
    }

    //采集网址
    public function colUrl() {
        $nodeid = input('param.id/d',0);
        if(!$nodeid){
            $this->error('参数错误');
        }
        if ($data = $this->get_one($this->db,['nodeid'=>$nodeid])) {
            $urls = Collection::url_list($data);
            $total_page = count($urls);
            if ($total_page > 0) {
                $page       = input('param.page/d',0);
                if($total_page == $page){
                    $this->db->where( ['nodeid'=>$nodeid])->update(['lastdate'=>time()]);
                    $this->success('网址采集完成，即将采集内容',url('colContent',['id'=>$nodeid,'status'=>2]),5);
                }
                $url_list   = $urls[$page];
                $url        = Collection::get_url_lists($url_list, $data);
                $history_db = db('CollectionHistory');
                $content_db = db('CollectionContent');
                $total      = count($url);
                $re         = 0;
                if (is_array($url) && !empty($url)) foreach ($url as $v) {
                    if (empty($v['url']) || empty($v['title'])) continue;
                    $v = new_addslashes($v);
                    $v['title'] = strip_tags($v['title']);
                    $md5 = md5($v['url']);
                    if (!$this->get_one($history_db,array('md5'=>$md5))) {
                        $history_db->insert(['md5'=>$md5]);
                        $content_db->insert(['nodeid'=>$nodeid, 'status'=>0, 'url'=>$v['url'], 'title'=>$v['title']]);
                    } else {
                        $re++;
                    }
                }
                $this->assign('url_list',$url_list);
                $this->assign('total',$total);
                $this->assign('page',$page);
                $this->assign('re',$re);
                $this->assign('total_page',$total_page);
                $this->assign('nodeid',$nodeid);
                $this->assign('url',$url);
                return $this->fetch();
            } else {
                $this->error('网址列表为空');
            }
        } else {
           $this->error('采集点不存在');
        }
    }

    //采集文章
    public function colContent() {
        $nodeid = input('param.id/d',0);
        if(!$nodeid) $this->error('参数错误');
        if ($data = $this->get_one($this->db,['nodeid'=>$nodeid])) {
            $content_db = db('CollectionContent');
            $page  = input('param.page/d',1);
            $total = input('param.total/d',0);
            if (empty($total)) $total = $content_db->where(['nodeid'=>$nodeid, 'status'=>0])->count();
            $total_page = ceil($total/2);
            $list = $content_db->where(['nodeid'=>$nodeid, 'status'=>0])->field('id,url')->order('id desc')->limit(2)->select();
            $i = 0;
            if (!empty($list) && is_array($list)) {
                foreach ($list as $v) {
                    $GLOBALS['downloadfiles'] = [];
                    $html = Collection::get_content($v['url'], $data);
                    $content_db->where(['id'=>$v['id']])->update(['status'=>1, 'data'=>array2string($html)]);
                    $i++;
                }
            } else {
                $this->error('请先采集网址');
            }

            if ($total_page > $page) {
                $url = url('colContent',['page'=>($page+1),'id'=>$nodeid,'total'=>$total]);
                $this->success('采集正在进行中，采集进度:'.($i+($page-1)*2).'/'.$total,$url,1);
            } else {
                $this->db->where(['nodeid'=>$nodeid])->save(['lastdate'=>time()]);
               $this->success('采集成功',url('index',['menuid'=>230]));
            }
        }
    }

    //文章列表
    public function publish() {
        $nodeid = input('param.id/d',0);
        if(!$nodeid) $this->error('参数错误');
        $node       = $this->get_one($this->db,['nodeid'=>$nodeid], 'name');
        $content_db = db('CollectionContent');
        $status     = input('param.status/d',0);
        $sql        = ['nodeid'=>$nodeid];
        if ($status) {
            $sql['status'] = $status - 1;
        }
        $this->assign('list_table',true);
        $data = $this->listinfo($content_db,$sql,20,'id desc');
        $this->assign('nodeid',$nodeid);
        $this->assign('name',$node['name']);
        $this->assign('lists',$data['lists']);
        $this->assign('pages',$data['pages']);
        $this->assign('status',$status);
        return $this->fetch();
    }

    //导入文章
    public function import() {
        $nodeid = input('param.nodeid/d',0);
        if(!$nodeid) $this->ajaxReturn(0,'参数错误');
        $id        = input('param.id',0);
        $type      = input('param.type');
        $programid = input('param.programid',0);
        $ids       = '';
        if ($type == 'all') {

        } else {
            $ids = urldecode($id);
        }
        $program_db   = db('CollectionProgram');
        $program_list = $program_db->where(['nodeid'=>$nodeid])->field('id, catid')->select();
        $node_data    = $this->get_one($this->db,['nodeid'=>$nodeid], "customize_config");
        $node_data['customize_config'] = string2array($node_data['customize_config']);
        $node_field = [''=>'请选择','title'=>'标题', 'source'=>'来源', 'content'=>'内容'];
        if (is_array($node_data['customize_config'])) foreach ($node_data['customize_config'] as $k=>$v) {
            if (empty($v['en_name']) || empty($v['name'])) continue;
            $node_field[$v['en_name']] = $v['name'];
        }
        $this->assign('nodeField',$node_field);
        $fields = ['title'=>'标题','description'=>'摘要','info'=>'内容','comefrom'=>'来源'];
        $this->assign('model',$fields);
        $this->assign('ids',$ids);
        $this->assign('type',$type);
        $this->assign('nodeid',$nodeid);
        $this->assign('programList',$program_list);
        $this->assign('programid',$programid);
        return $this->fetch();
    }
//添加导入方案
    public function importProgramAdd() {
        $nodeid = input('param.nodeid',0);
        $ids    = input('param.ids');
        $catid  = input('param.cateid',0);
        $type   = input('param.type');
        if(!$nodeid){
            $this->error('采集点不存在');
        }
        if(!$catid){
            $this->error('请选择分类');
        }
        if(request()->isPost()){
            if($id=$this->addProgram($nodeid,$catid)){
                $this->success('添加发布方案成功',url('import',['programid'=>$id,'nodeid'=>$nodeid,'type'=>$type,'id'=>urlencode($ids)]));
            }else{
                $this->error('添加失败');
            }
        }
    }

    //删除文章
    public function contentdel() {
        $mod     = db('CollectionContent');
        $pk      = $mod->getPk();
        $ids     = trim(input('param.id'), ',');
        $history = input('param.history',0);
        if ($ids) {
            if($history){
                $history_db = db("CollectionHistory");
               $list = $mod->where(['id'=>['in',$ids]])->field('url')->select();
                $md5 = [];
                foreach ($list as $v) {
                    $md5[] = md5($v['url']);
                }
                $history_db->where(['md5'=>['in',$md5]])->delete();
            }
            if (false !== $mod->where(array('id'=>['in',$ids]))->delete()) {
                request()->isAjax() && $this->ajaxReturn(1, '操作成功');
                $this->success('操作成功');
            } else {
                request()->isAjax() && $this->ajaxReturn(0, '操作失败');
                $this->error('操作失败');
            }
        } else {
            request()->isAjax() && $this->ajaxReturn(0, '参数错误');
            $this->error('参数错误');
        }

    }

    public function importProgramDel() {
        $id = input('param.id',0);
        if(!$id){
            $this->error('参数错误');
        }
        $program_db = db('CollectionProgram');
        if ($program_db->where(['id'=>$id])->delete()) {
            $this->success('删除成功');
        } else {
           $this->error('删除失败');
        }
    }

    //导入文章到模型
    public function importContent() {
        $nodeid    = input('param.nodeid',0);
        $programid = input('param.programid',0);
        $ids       = input('param.ids');
        $type      = input('param.type');
        $starttype = input('param.stime',1);//时间类型
        $startTime = input('param.start',0);//开始时间
        $sendnum   = input('param.sendnum',1);//发布篇数
        $random    = input('param.random');
        if($sendnum==1 || $sendnum==2 || $sendnum==4 || $sendnum==5){
            $pagesize = 20;
        }elseif($sendnum==3 || $sendnum==6){
            $pagesize = 21;
        }else{
            $pagesize = $sendnum*3;
        }

        if (!$node = $this->get_one($this->db,['nodeid'=>$nodeid], 'coll_order,content_page')) {
           $this->error('采集点不存在',url('index',array('menuid'=>230)));
        }
        if(!$programid){
           $this->error('方案id不存在');
        }
        if(!$startTime){
            switch($starttype){
                case 1:
                    $startTime = time();
                    break;
                case 2:
                    $startTime = strtotime(input('param.time_start'));
                    break;
                default:
                    $startTime = time();
                    break;
            }
        }

        $program_db            = db('CollectionProgram');
        $collection_content_db = db('CollectionContent');
        $content_db            = db('Article');

        $order = $node['coll_order'] == 1 ? 'id desc' : '';
        $str = '导入成功';
        $url = url('publish',['id'=>$nodeid,'status'=>2]);
        if ($type == 'all') {
            $total = isset($_GET['total']) && intval($_GET['total']) ? intval($_GET['total']) : '';
            if (empty($total)) $total = $collection_content_db->where(['nodeid'=>$nodeid, 'status'=>1])->count();
            $total_page = ceil($total/$pagesize);
            $page       = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
            $total_page = ceil($total/$pagesize);
            $data       = $collection_content_db->where(['nodeid'=>$nodeid, 'status'=>1])->order($order)->field('id,data')->limit($pagesize)->select();

        } else {
            $data  = $collection_content_db->where(['id'=>['in',$ids],'nodeid'=>$nodeid,'status' =>1])->field('id,data')->order($order)->select();
            $total = count($data);
            $str = $total.'篇文章被导入';
        }
        $program = $program_db->where(['id'=>$programid])->find();
        $program['config'] = string2array($program['config']);

        $i = 0;
        $n = 0;
        $coll_contentid = array();
        $catearr = array();
        if($random == 1){
            $catelist = model("ArticleCate")->where(['status'=>1])->field('id')->select();
            foreach($catelist as $cat){
                $catearr[$cat['id']] = $cat['id'];
            }
        }

        foreach ($data as $k=>$v) {
            $cate_id = $random == 1 ? array_rand($catearr) : $program['catid'];
            $sql = ['cate_id'=>$cate_id, 'status'=>$program['config']['content_status']];
            $v['data'] = string2array($v['data']);

            foreach ($program['config']['map'] as $a=>$b) {
                if (isset($program['config']['funcs'][$a]) && function_exists($program['config']['funcs'][$a])) {
                    $GLOBALS['field'] = $a;
                    $sql[$a] = $program['config']['funcs'][$a]($v['data'][$b]);
                } else {
                    $sql[$a] = $v['data'][$b];
                }
            }
            $title = trim(strip_tags($v['data']['title']));
            $content = trim(strip_tags($v['data']['content']));

            if($k%$sendnum == 0 && $k>0){
                $n++;
            }
            $start    = strtotime(date("Y-m-d",strtotime("+".$n." day",$startTime)));
           $adddata = $this->setData($sql,$program['config']);
            $adddata['create_time'] = $this->_setTime($start);
            if($content && $title){
                $content_db->insert($adddata);
                $contentid = $content_db->getLastInsID();
                if ($contentid) {
                    $coll_contentid[] = $v['id'];
                    $i++;

                } else {
                    $collection_content_db->where(['id'=>$v['id']])->delete();
                }
            }

        }

        $sql_id = implode(',', $coll_contentid);
        $collection_content_db->where(['id'=>['in',$sql_id]])->update(['status'=>2]);
        if ($type == 'all' && $total_page > $page) {
            $str = '正在导入中，导入进度：'.(($page-1)*$pagesize+$i).'/'.$total;
            $url = url('importContent',['start'=>strtotime("+1 days",$start),'random'=>$random,'sendnum'=>$sendnum,'nodeid'=>$nodeid,'programid'=>$programid,'type'=>'all','page'=>($page+1),'total'=>$total]);
        }
       $this->success($str,$url);
    }
    private function setData($data,$config){
        if($config['add_introduce'] == 1){
            $len = $config['introcude_length'];
            $content = stripslashes($data['info']);
            $data['description'] = msubstr(str_replace(array("'","\r\n","\t",'[page]','[/page]','&ldquo;','&rdquo;','&nbsp;'), '', strip_tags($content)),0,$len);
            $data['description'] = addslashes($data['description']);
        }
        if($config['auto_thumb'] == 1){
            $num = $config['auto_thumb_no'];
            $num = $num - 1;
            $content = stripslashes($data['info']);
            if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
                $data['img'] = $matches[3][$num];
            }
        }
        return $data;
    }
    private function _setTime($start){

        $s = strtotime(date("Y-m-d 08:00:00",$start));
        $e = strtotime(date("Y-m-d 18:00:00",$start));
        return mt_rand($s,$e);
    }
    private function addProgram($nodeid,$catid){
        $config      = [];
        $model_field = isset($_POST['model_field']) ? $_POST['model_field'] : '';
        $node_field  = isset($_POST['node_field']) ? $_POST['node_field'] : '';
        $funcs       = isset($_POST['funcs']) ? $_POST['funcs'] : array();
        if(!$model_field){
            $this->error('原数据表字段不存在');
        }
        if(!$node_field){
            $this->error('采集字段不存在');
        }
        $config['add_introduce']    = isset($_POST['add_introduce']) && intval($_POST['add_introduce']) ? intval($_POST['add_introduce']) : 0;
        $config['auto_thumb']       = isset($_POST['auto_thumb']) && intval($_POST['auto_thumb']) ? intval($_POST['auto_thumb']) : 0;
        $config['introcude_length'] = isset($_POST['introcude_length']) && intval($_POST['introcude_length']) ? intval($_POST['introcude_length']) : 0;
        $config['auto_thumb_no']    = isset($_POST['auto_thumb_no']) && intval($_POST['auto_thumb_no']) ? intval($_POST['auto_thumb_no']) : 0;
        $config['content_status']   = isset($_POST['content_status']) && intval($_POST['content_status']) ? intval($_POST['content_status']) : 1;

        foreach ($node_field as $k => $v) {
            if (empty($v)) continue;
            $config['map'][$model_field[$k]] = $v;
        }

        foreach ($funcs as $k=>$v) {
            if (empty($v)) continue;
            $config['funcs'][$model_field[$k]] = $v;
        }

        $data = ['config'=>array2string($config), 'nodeid'=>$nodeid, 'modelid'=>0, 'catid'=>$catid];
        $program_db = db('CollectionProgram');
        if ($id = $program_db->insert($data)) {
           return $program_db->getLastInsID();
        } else {
           return false;
        }
    }
}